<template>
    <a-modal :open :width :title="title ?? customTitle" :footer destroyOnClose @cancel="close" @ok="validate">
        <CustomForm ref="FormRef" :rules="rules" :FormValue="FormValue" :options="FormConfig!.options"
            :labelCol="FormConfig!.labelCol" :labelAlign="FormConfig!.labelAlign" :layout="FormConfig!.layout">
        </CustomForm>
        <slot />
        <template v-if="$slots.footer" #footer>
            <slot name="footer" />
        </template>
    </a-modal>
</template>
<script lang='ts' setup>
import { computed, ref, nextTick } from 'vue';
import { message } from 'ant-design-vue'

interface Props {
    type?: string,
    title?: string,
    width?: string | number,
    footer?: string | Function,
    okFn?: Function,
    rules?: Object,
    FormValue: Object,
    FormConfig: FormConfig
}

interface FormConfig {
    labelCol: { span: number },
    labelAlign: string,
    layout: string,
    options: []
}

const props = defineProps<Props>()
const FormRef = ref()
const open = defineModel("open", { type: Boolean, default: false })

const customTitle = computed(
    () => {
        let title
        switch (props.type) {
            case 'add':
                title = '添加'
                break;
            case 'edit':
                title = '修改'
                break;
            case 'export':
                title = '导出'
                break;
            default:
                title = ''
                break;
        }
        return title
    }
)
function close() {
    FormRef.value.resetFields()
    open.value = false
}

function validate() {
    nextTick(() => {
        FormRef.value.Form.validate()
            .then(async (res: any) => {
                if (props.okFn) {
                    await props.okFn()
                }
                close()
            })
            .catch((err: any) => {
                message.error('表单校验失败！')
            })
    })
}

defineExpose({ open, validate })

</script>
<style scoped></style>